/**
 * Created by ryansecreat on 2017/12/22.
 */
const os     = require( "os" );
const crypto = require( "crypto" );
const exec   = require( "child_process" ).exec;
const fs     = require( "fs" );

module.exports = {

    formatName( name )
    {
        return `gogers ${name}`;
    },
    sha1( input ) {
        let shasum = crypto.createHash( 'sha1' );
        shasum.update( input );
        return shasum.digest( 'hex' );
    },
    md5( input ) {
        let md5 = crypto.createHash( "md5" );
        md5.update( input );
        return md5.digest( "hex" );
    },

    killByPort( port ) {
        if (!port) {
            return
        }
        exec( `kill -9 $(lsof -t -i:${port})` )
    },
    sleep( time ) {
        return new Promise( resolve => setTimeout( resolve, time ) );
    },
    promisify( fn, receiver ) {
        return ( ...args ) => {
            return new Promise( ( resolve, reject ) => {
                fn.apply( receiver, [...args, ( err, res ) => {
                    return err ? reject( err ) : resolve( res );
                }] );
            } );
        }
    },
    defer() {
        const deferred   = {};
        deferred.promise = new Promise( ( resolve, reject ) => {
            deferred.resolve = resolve;
            deferred.reject  = reject;
        } );
        return deferred;
    },
    omit( obj, props )
    {
        let result = {};
        Object.keys( obj ).forEach( item => {
            if (!props.include( item ))
                result[item] = obj[item];
        } )
        return result;
    },
    isExist( dir ) {
        dir = path.normalize( dir );
        try {
            fs.accessSync( dir, fs.R_OK );
            return true;
        } catch (e) {
            return false;
        }
    },
    random( lower, upper ) {
        if (lower === undefined && upper === undefined) {
            return 0;
        }
        if (upper === undefined) {
            upper = lower;
            lower = 0;
        }
        var temp;
        if (lower > upper) {
            temp  = lower;
            lower = upper;
            upper = temp;
        }
        return Math.floor( lower + Math.random() * (upper - lower) );
    }

};